<template>
  <NuxtLayout name="admin" menuActive="/admin/curriculum">
    <div class="card">
      <el-page-header @back="useRouter().go(-1)">
        <template #content>
          <el-input v-model="listForm.keyword" placeholder="请输入标题">
            <template #append>
              <el-button :icon="Search" @click="searchFn"></el-button>
            </template>
          </el-input>
        </template>
        <template #extra>
          <el-button @click="addFn">添加课程</el-button>
        </template>
      </el-page-header>
      <div style="height: 18px;"></div>
      <el-table class="my_table" :data="tableData" border show-overflow-tooltip>
        <el-table-column prop="title" label="课程标题" width="400" />
        <el-table-column prop="subject.name" label="科目" />
        <el-table-column prop="imgs" label="封面图" width="130">
          <template #default="scope">
            <el-image style="width: 100px;height: 100px;" :src="scope.row.imgs[0]"
              :preview-src-list="[scope.row.imgs[0]]" preview-teleported fit="cover"
              v-show="scope.row.imgs.length > 0" />
          </template>
        </el-table-column>
        <el-table-column label="讲师">
          <template #default="scope">
            <el-tag v-for="item in scope.row.teachers" :key="item.id">{{ item.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="brief" label="内容简介" />
        <el-table-column prop="introduce" label="目标介绍" />
        <el-table-column label="内容详情">
          <template #default="scope">
            <div class="detail" @click="detailFn(scope.row.content)" v-show="scope.row.content">查看</div>
          </template>
        </el-table-column>
        <el-table-column prop="dayOfHours" label="每日最多学时" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="vip" label="会员级别" />
        <el-table-column prop="learns" label="学习数" />
        <el-table-column prop="likes" label="点赞数" />
        <el-table-column prop="collects" label="收藏数" />
        <el-table-column prop="shares" label="分享数" />
        <el-table-column prop="starLevel" label="推荐星级" width="146">
          <template #default="scope">
            <el-rate v-model="scope.row.starLevel" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="scoreLevel" label="评分" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column label="是否启用">
          <template #default="scope">
            <el-tag type="success" v-show="scope.row.enabled == 1">启用</el-tag>
            <el-tag type="info" v-show="scope.row.enabled == 0">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="100">
          <template #default="scope">
            <el-tag type="info" v-show="scope.row.auditStatus == 0">未审核</el-tag>
            <el-tag type="success" v-show="scope.row.auditStatus == 1">审核通过</el-tag>
            <el-tag type="danger" v-show="scope.row.auditStatus == 2">审核驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" />
        <el-table-column prop="auditMsg" label="审核信息" />
        <el-table-column prop="publishedTime" label="发布时间" />
        <el-table-column label="操作" fixed="right" width="255">
          <template #default="scope">
            <a class="el-button el-button--warning el-button--small" :href="`/admin/chapter/${scope.row.id}`">章节</a>
            <a class="el-button el-button--primary el-button--small" :href="`/admin/video/${scope.row.id}`">视频</a>
            <el-button type="success" size="small" @click="editFn(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="delFn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card_pagin">
        <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="listForm.pageSize"
          @change="pageChangeFn" />
      </div>
    </div>
    <MyForm :visible="formVisible" :forms="form" :title="formTitle" @pick="formPickFn" />
    <el-dialog v-model="detailVisible" title="内容详情" :show-close="false" width="800">
      <div v-html="detailValue"></div>
    </el-dialog>
  </NuxtLayout>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { courseList, addCourse, updateCourse, deleteCourse, getCourseApi } from '~/server/api'
import { formatTime } from '~/utils/utils'
import MyForm from './form'
// TDK
const prevHost = useRequestHeaders()["x-forwarded-proto"];
const host = useRequestHeaders()["host"];
const fullPath = useRoute()["fullPath"];
useSeoMeta({
  title: "技考邦_课程管理",
  keywords: "技考邦,课程管理",
  description: "技考邦，课程管理。",
  ogTitle: "技考邦_课程管理",
  ogDescription: "技考邦，课程管理。",
  ogType: "article",
  ogUrl: `${prevHost}://${host}${fullPath}`,
});
const listForm = ref({
  pageNum: 1,
  pageSize: 20,
  keyword: ''
})
// 搜索
const searchFn = () => {
  listForm.value.pageNum = 1;
  getList()
}
// 列表
const tableData = ref([])
const total = ref(0)
const getList = async () => {
  let { data: listRes } = await useAsyncData('courseList', () => useServerRequest(courseList, {
    method: 'post',
    body: JSON.stringify(listForm.value)
  }))
  if (listRes.value && listRes.value.errno === 0) {
    tableData.value = listRes.value.result.list;
    total.value = listRes.value.result.total;
  }
}
getList()
// 获取课程详情
async function getInfoFn(courseId) {
  let res = await useServerRequest(getCourseApi, {
    method: 'get',
    params: { courseId }
  })
  if (res && res.errno === 0 && res.result) {
    form.value.content = res.result.content || '';
  }
}
// 添加
const formVisible = ref(false)
const formTitle = ref('')
const form = ref({
  id: '',
  subjectId: '',
  title: '',
  imgs: [],
  teacherIds: [],
  // teacherName: '',
  brief: '',
  introduce: '',
  content: '',
  dayOfHours: 0,
  amount: 0,
  vip: 0,
  learns: 1,
  likes: 1,
  collects: 1,
  shares: 1,
  starLevel: 5,
  scoreLevel: 10,
  publishedTime: formatTime(new Date().getTime()),
  enabled: false,
  sort: 0
})
const addFn = () => {
  form.value.id = '';
  form.value.subjectId = '';
  form.value.title = '';
  form.value.imgs = [];
  form.value.teacherIds = [];
  // form.value.teacherName = '';
  form.value.brief = '';
  form.value.introduce = '';
  form.value.content = '';
  form.value.dayOfHours = 0;
  form.value.amount = 0;
  form.value.vip = 0;
  form.value.learns = 1;
  form.value.likes = 1;
  form.value.collects = 1;
  form.value.shares = 1;
  form.value.starLevel = 5;
  form.value.scoreLevel = 10;
  form.value.publishedTime = formatTime(new Date().getTime());
  form.value.enabled = true;
  form.value.sort = 0;
  formTitle.value = '添加课程';
  formVisible.value = true;
}
// 分页
const pageChangeFn = (val) => {
  listForm.value.pageNum = val;
  getList()
}
// 查看内容详情
const detailVisible = ref(false)
const detailValue = ref('')
const detailFn = (val) => {
  detailValue.value = val;
  detailVisible.value = true;
}
// 编辑
const editFn = (val) => {
  getInfoFn(val.id)
  form.value.id = val.id;
  form.value.subjectId = val.subjectId;
  form.value.title = val.title;
  form.value.imgs = val.imgs;
  form.value.teacherIds = val.teacherIds;
  // form.value.teacherName = val.teachers ? val.teachers.name : '';
  form.value.brief = val.brief;
  form.value.introduce = val.introduce;
  // form.value.content = val.content;
  form.value.dayOfHours = val.dayOfHours;
  form.value.amount = val.amount;
  form.value.vip = val.vip;
  form.value.learns = val.learns;
  form.value.likes = val.likes;
  form.value.collects = val.collects;
  form.value.shares = val.shares;
  form.value.starLevel = val.starLevel;
  form.value.scoreLevel = val.scoreLevel;
  form.value.publishedTime = val.publishedTime;
  form.value.enabled = val.enabled;
  form.value.sort = val.sort;
  formTitle.value = '编辑课程';
  formVisible.value = true;
}
// 删除
const delFn = (val) => {
  ElMessageBox.confirm('是否删除当前数据', {
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then(async () => {
    let delRes = await useServerRequest(deleteCourse, {
      method: 'post',
      body: JSON.stringify({
        id: val.id
      })
    })
    if (delRes.errno === 0) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getList()
      return false;
    }
  }).catch(() => {})
}
// 确认
const formPickFn = async (e) => {
  if (e.form) {
    const loading = ElLoading.service({ text: '请求中...', target: document.querySelector('.el-dialog') })
    let url = e.form.id ? updateCourse : addCourse;
    let courseRes = await useServerRequest(url, {
      method: 'post',
      body: JSON.stringify(e.form)
    })
    if (courseRes.errno === 0) {
      ElMessage({
        message: e.form.id ? '修改成功' : '添加成功',
        type: 'success'
      })
      getList()
      formVisible.value = e.visible;
    }
    loading.close()
    return false;
  }
  formVisible.value = e.visible;
}
</script>

<style lang="less" scoped>
.card {
  background: #FFFFFF;
  border-radius: 10px;
  border: 1px solid #EEEEEE;
  padding: 35px 25px;

  &_pagin {
    margin-top: 30px;
    display: flex;
    justify-content: center;
  }

  .detail {
    cursor: pointer;
    color: #2C6EFF;
  }
}
</style>